<template>
  <Modal
    :title="user ? '编辑用户' : '创建用户'"
    @close="$emit('close')"
  >
    <form @submit.prevent="handleSubmit" class="space-y-4">
      <!-- 基本信息 -->
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            用户名 <span class="text-red-500">*</span>
          </label>
          <input
            v-model="formData.username"
            type="text"
            required
            class="input w-full"
            :class="{ 'border-red-500': errors.username }"
            placeholder="请输入用户名"
          >
          <p v-if="errors.username" class="mt-1 text-sm text-red-600">
            {{ errors.username }}
          </p>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            邮箱 <span class="text-red-500">*</span>
          </label>
          <input
            v-model="formData.email"
            type="email"
            required
            class="input w-full"
            :class="{ 'border-red-500': errors.email }"
            placeholder="请输入邮箱"
          >
          <p v-if="errors.email" class="mt-1 text-sm text-red-600">
            {{ errors.email }}
          </p>
        </div>
      </div>

      <!-- 密码 -->
      <div v-if="!user" class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            密码 <span class="text-red-500">*</span>
          </label>
          <div class="relative">
            <input
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              required
              class="input w-full pr-10"
              :class="{ 'border-red-500': errors.password }"
              placeholder="请输入密码"
            >
            <button
              type="button"
              @click="showPassword = !showPassword"
              class="absolute inset-y-0 right-0 pr-3 flex items-center"
            >
              <i :class="showPassword ? 'mdi:eye-off' : 'mdi:eye'" class="w-5 h-5 text-gray-400" />
            </button>
          </div>
          <p v-if="errors.password" class="mt-1 text-sm text-red-600">
            {{ errors.password }}
          </p>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            确认密码 <span class="text-red-500">*</span>
          </label>
          <div class="relative">
            <input
              v-model="formData.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              required
              class="input w-full pr-10"
              :class="{ 'border-red-500': errors.confirmPassword }"
              placeholder="请确认密码"
            >
            <button
              type="button"
              @click="showConfirmPassword = !showConfirmPassword"
              class="absolute inset-y-0 right-0 pr-3 flex items-center"
            >
              <i :class="showConfirmPassword ? 'mdi:eye-off' : 'mdi:eye'" class="w-5 h-5 text-gray-400" />
            </button>
          </div>
          <p v-if="errors.confirmPassword" class="mt-1 text-sm text-red-600">
            {{ errors.confirmPassword }}
          </p>
        </div>
      </div>

      <!-- 角色选择 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">
          角色 <span class="text-red-500">*</span>
        </label>
        <div class="space-y-2">
          <label
            v-for="role in roles"
            :key="role.id"
            class="flex items-center"
          >
            <input
              v-model="formData.roleIds"
              type="checkbox"
              :value="role.id"
              class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
            >
            <span class="ml-2 text-sm text-gray-700">{{ role.name }}</span>
          </label>
        </div>
        <p v-if="errors.roleIds" class="mt-1 text-sm text-red-600">
          {{ errors.roleIds }}
        </p>
      </div>

      <!-- 状态 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
        <div class="flex items-center space-x-4">
          <label class="flex items-center">
            <input
              v-model="formData.status"
              type="radio"
              value="active"
              class="text-blue-600 border-gray-300 focus:ring-blue-500"
            >
            <span class="ml-2 text-sm text-gray-700">激活</span>
          </label>
          <label class="flex items-center">
            <input
              v-model="formData.status"
              type="radio"
              value="inactive"
              class="text-blue-600 border-gray-300 focus:ring-blue-500"
            >
            <span class="ml-2 text-sm text-gray-700">禁用</span>
          </label>
        </div>
      </div>

      <!-- 头像上传 -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">头像</label>
        <div class="flex items-center space-x-4">
          <img
            :src="formData.avatar || `https://via.placeholder.com/64x64/3b82f6/ffffff?text=${formData.username.charAt(0) || 'U'}`"
            :alt="formData.username"
            class="w-16 h-16 rounded-full object-cover"
          >
          <div>
            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              @change="handleFileChange"
              class="hidden"
            >
            <button
              type="button"
              @click="$refs.fileInput.click()"
              class="btn-secondary"
            >
              选择头像
            </button>
            <p class="mt-1 text-xs text-gray-500">
              支持 JPG、PNG 格式，大小不超过 2MB
            </p>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end space-x-3 pt-4 border-t">
        <button
          type="button"
          @click="$emit('close')"
          class="btn-secondary"
        >
          取消
        </button>
        <button
          type="submit"
          :disabled="loading"
          class="btn-primary"
        >
          <i v-if="loading" class="w-4 h-4 mr-2 animate-spin mdi:loading" />
          {{ user ? '更新' : '创建' }}
        </button>
      </div>
    </form>
  </Modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import Modal from '@/components/Modal.vue'

interface User {
  id: string
  username: string
  email: string
  avatar?: string
  roles: string[]
  status: 'active' | 'inactive'
}

interface Role {
  id: string
  name: string
}

interface Props {
  user?: User | null
  roles: Role[]
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
  save: [data: any]
}>()

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  roleIds: [] as string[],
  status: 'active' as 'active' | 'inactive',
  avatar: ''
})

const errors = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  roleIds: ''
})

// 监听用户数据变化，初始化表单
watch(() => props.user, (user) => {
  if (user) {
    formData.username = user.username
    formData.email = user.email
    formData.status = user.status
    formData.avatar = user.avatar || ''
    // 根据角色名称找到对应的ID
    formData.roleIds = props.roles
      .filter(role => user.roles.includes(role.name))
      .map(role => role.id)
  } else {
    // 重置表单
    Object.assign(formData, {
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      roleIds: [],
      status: 'active',
      avatar: ''
    })
  }
  // 清除错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
}, { immediate: true })

// 验证表单
const validateForm = () => {
  let isValid = true
  
  // 清除之前的错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })

  // 验证用户名
  if (!formData.username.trim()) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (formData.username.length < 3) {
    errors.username = '用户名至少3个字符'
    isValid = false
  }

  // 验证邮箱
  if (!formData.email.trim()) {
    errors.email = '请输入邮箱'
    isValid = false
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址'
    isValid = false
  }

  // 验证密码（仅在创建用户时）
  if (!props.user) {
    if (!formData.password) {
      errors.password = '请输入密码'
      isValid = false
    } else if (formData.password.length < 6) {
      errors.password = '密码至少6个字符'
      isValid = false
    }

    if (!formData.confirmPassword) {
      errors.confirmPassword = '请确认密码'
      isValid = false
    } else if (formData.password !== formData.confirmPassword) {
      errors.confirmPassword = '两次输入的密码不一致'
      isValid = false
    }
  }

  // 验证角色
  if (formData.roleIds.length === 0) {
    errors.roleIds = '请至少选择一个角色'
    isValid = false
  }

  return isValid
}

// 处理文件上传
const handleFileChange = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    // 验证文件大小
    if (file.size > 2 * 1024 * 1024) {
      alert('文件大小不能超过2MB')
      return
    }

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件')
      return
    }

    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    // 准备提交数据
    const submitData = {
      username: formData.username,
      email: formData.email,
      status: formData.status,
      avatar: formData.avatar,
      roleIds: formData.roleIds
    }

    // 如果是创建用户，包含密码
    if (!props.user) {
      submitData.password = formData.password
    }

    emit('save', submitData)
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>